<template>
  <div>
    <!-- 左侧菜单 -->
    <div
      v-if="!visible"
      class="left-menu-container left-menu"
      :style="{
        right: visible ? '0%' : '0%',
        zIndex: 3,
      }"
    >
      <div
        v-if="!visible"
        class="menu-item info-icon"
        @click="handleInfoClick"
        title="展开详情"
      >
        <img src="../assets/arrowLeft.svg" alt="" />
      </div>
      <div
        v-else
        class="menu-item info-icon"
        @click="closeInfoClick"
        title="收起详情"
      >
        <img src="../assets/arrowRight.svg" alt="" />
      </div>
      <div
        class="menu-item"
        :class="{ active: menuId === 1 }"
        @click="handleMenuItemClick(1)"
        title="详情"
      >
        <img src="../assets/taskInfo.svg" alt="详情" class="menu-icon" />
      </div>
      <div
        class="menu-item"
        :class="{ active: menuId === 2 }"
        @click="handleMenuItemClick(2)"
        title="数据流"
      >
        <img src="../assets/taskFlow.svg" alt="" class="menu-icon" />
      </div>
      <div
        class="menu-item"
        :class="{ active: menuId === 3 }"
        @click="handleMenuItemClick(3)"
        title="版本"
      >
        <img src="../assets/taskVersion.svg" alt="" class="menu-icon" />
      </div>
    </div>

    <el-drawer
      resizable
      style="--el-drawer-padding-primary: 0px"
      v-model="visible"
      direction="rtl"
      size="100%"
      :before-close="handleClose"
      :with-header="false"
      :modal="false"
      :modal-penetrable="true"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :z-index="100"
      @click="handleResize"
    >
      <div
        class="left-menu-container left-menu"
        :style="{
          zIndex: 3,
          left: '-40px',
        }"
      >
        <div
          v-if="!visible"
          class="menu-item info-icon"
          @click="handleInfoClick"
          title="展开详情"
        >
          <img src="../assets/arrowLeft.svg" alt="" />
        </div>
        <div
          v-else
          class="menu-item info-icon"
          @click="closeInfoClick"
          title="收起详情"
        >
          <img src="../assets/arrowRight.svg" alt="" />
        </div>
        <div
          class="menu-item"
          :class="{ active: menuId === 1 }"
          @click="handleMenuItemClick(1)"
          title="详情"
        >
          <img src="../assets/taskInfo.svg" alt="详情" class="menu-icon" />
        </div>
        <div
          class="menu-item"
          :class="{ active: menuId === 2 }"
          @click="handleMenuItemClick(2)"
          title="数据流"
        >
          <img src="../assets/taskFlow.svg" alt="" class="menu-icon" />
        </div>
        <div
          class="menu-item"
          :class="{ active: menuId === 3 }"
          @click="handleMenuItemClick(3)"
          title="版本"
        >
          <img src="../assets/taskVersion.svg" alt="" class="menu-icon" />
        </div>
      </div>
      <div class="noData" v-if="!record?.id">暂无数据</div>
      <div v-else class="panel" v-loading="loading">
        <div
          class="left-panel"
          :key="JSON.stringify(detail ?? {})"
          :style="{
            width: !showDetail ? '100%' : '0px',
            minWidth: '600px',
          }"
        >
          <div
            :style="{
              transform: showDetail ? 'rotate(0deg)' : 'rotate(180deg)',
            }"
            class="left-arrow"
            @click.stop="handleArrow"
          >
            <img
              style="display: inline-block; margin-right: 3px"
              src="@/assets/wbs/rightRound.svg"
              alt=""
            />
          </div>
          <DrawHeader
            :detail="detail"
            :activeTab="activeTab"
            :record="record"
            :childrenList="childrenList"
            :nameChange="nameChange"
          />
          <el-tabs
            size="small"
            style="
              --el-color-primary: #1aa1fb;
              --el-text-color-primary: #42464e;
              --el-font-size-base: 13px;
            "
            v-model="activeTab"
            class="tab-title"
          >
            <el-tab-pane
              v-for="item in computedTabItems"
              :name="item.type"
              :key="item.type"
            >
              <template #label>
                <div>
                  <span
                    :style="{
                      fontWeight: Object.is(activeTab, item.type) ? 500 : 400,
                    }"
                  >
                    {{ item.title }}</span
                  >

                  <span v-if="[6].includes(item.id)"
                    >({{
                      (childrenList ?? record?.children)?.length ?? 0
                    }})</span
                  >
                  <span v-if="[7].includes(item.id)">({{ relateCount }})</span>
                </div>
              </template>
              <div class="tabs-detail">
                <keep-alive>
                  <component
                    v-if="activeTab == item.type"
                    :is="item.type"
                    :item="item"
                    :key="item.type"
                    :detail="detail"
                    :subTask="subTask"
                    :asyncData="asyncData"
                  />
                </keep-alive>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div
          class="right-panel"
          :style="{
            display: showDetail ? 'block' : 'none',
            minWidth: '320px',
          }"
        >
          <div class="right-header">
            <div style="margin-right: auto">基础字段</div>
            <img
              style="display: inline-block; margin-right: 3px"
              src="@/assets/wbs/share.svg"
              alt=""
            />
          </div>

          <FormDetail
            :detail="detail"
            :data="formDataDetail"
            @update:data="updateFormData"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from "vue";
  import { componentsList, AllTabs } from "./wbsDraw/const.ts";
  import { getTaskDetail, taskEdit, getTaskDetailTitle } from "./wbsDraw/api";
  import DrawHeader from "./wbsDraw/DrawHeader.vue";
  import FormDetail from "@/components/wbsDraw/FormDetail.vue";
  import { nextTick } from "vue";

  const detail = ref<any>();
  const formDataDetail = computed(() => {
    const planned = [
      detail.value?.plannedStartTime ?? "",
      detail.value?.plannedEndTime ?? "",
    ];
    const actual = [
      detail.value?.actualStartTime ?? "",
      detail.value?.actualEndTime ?? "",
    ];
    return { ...detail.value, planned, actual };
  });
  const loading = ref(false);
  const showDetail = ref(true);
  const visible = ref(false);
  const formData = ref({});
  const formRef = ref<any>();
  const wbsFields = ref([]);
  const wbsData = ref([]);
  const activeTab = ref<string>("DrawDetail");
  const computedTabItems = ref(AllTabs);
  const childrenList = ref();
  const relateCount = ref(0);
  // 菜单项选中状态
  const menuId = ref<number>(0);
  // 记录最后一次点击菜单项的信息
  const lastMenuItemClick = ref<{ time: number; menuId: number }>({
    time: 0,
    menuId: 0,
  });
  defineOptions({
    components: componentsList,
  });
  const props = defineProps([
    "size",
    "fields",
    "record",
    "mode",
    "routerFields",
    "clearSelectRecord",
  ]);
  defineExpose({
    visible,
  });

  const emit = defineEmits();

  /**
   * @description 处理遮罩层
   */
  const handleResize = () => {
    const drawer = document.querySelector(".is-drawer");
    const panel = document.querySelector(".panel");
    if (drawer) {
      const width = window.getComputedStyle(panel)?.width + "";
      drawer.style.marginLeft = width.includes(".") ? "24.9%" : "100%";
    }
  };

  /**
   * @description 处理子任务变更
   */
  const subTask = (type: string, list: any) => {
    if (type === "subTask") {
      childrenList.value = list;
    } else {
      relateCount.value = list;
    }
  };

  /**
   * @description 处理名称变化
   */
  const nameChange = async (obj: any) => {
    detail.value.name = obj.name?.["zh_CN"] ?? obj.name;
    await nextTick();
    emit("update:formData", detail.value);
  };

  /**
   * @description 处理remark变化
   */
  const asyncData = async (obj: any) => {
    detail.value.remark = obj.remark;
    await nextTick();
    emit("update:formData", detail.value);
  };

  /**
   * @description 处理折叠按钮
   */
  const handleArrow = () => {
    showDetail.value = !showDetail.value;
  };

  const handleClose = (done: () => void) => {
    close();
    done();
  };

  const close = () => {
    formData.value = {};
    wbsData.value = [];
    wbsFields.value = [];
    // 重置表单验证状态
    if (formRef.value) {
      formRef.value.resetFields();
    }
  };

  // 确保handleInfoClick只定义一次
  function handleInfoClick() {
    visible.value = true;
    emit("visibleOp");
    if (menuId.value === 0) {
      menuId.value = 1;
    }
  }
  const closeInfoClick = () => {
    menuId.value = 0;
    visible.value = false;
    emit("visibleOp");
    props?.clearSelectRecord();
  };

  // 菜单项点击处理方法
  const handleMenuItemClick = (itemMenuId: number) => {
    menuId.value = itemMenuId;
    lastMenuItemClick.value = { time: Date.now(), menuId: itemMenuId };
  };

  /**
   * @description 处理详情变化，获取数据
   */
  const updateFormData = async (args: any) => {
    try {
      args.name = detail.value.name;
      args.remark = detail.value.remark;
      const params = { ...detail?.value, ...args };
      params.plannedStartTime = args.planned[0] ?? "";
      params.plannedEndTime = args.planned[1] ?? "";
      params.actualStartTime = args.actual[0] ?? "";
      params.actualEndTime = args.actual[1] ?? "";
      delete params.planned;
      delete params.actual;
      params.name = params.name?.["zh_CN"] ?? params.name;
      emit("update:formData", params);
      await taskEdit({
        ...params,
        name: {
          zh_CN: params.name,
        },
      });
      // 同步列表页
    } catch (error) {}
  };

  watch(
    () => props.record,
    async () => {
      loading.value = true;
      try {
        if (props?.record?.id) {
          const res = await getTaskDetail(props?.record?.id);
          const titleRes = await getTaskDetailTitle(props?.record?.id);
          relateCount.value =
            titleRes?.find((e: any) => e.name === "相关任务")?.count ?? 0;

          res.lifecycleCurrentNode.process ??= 0;
          detail.value = res ?? {};
        }
      } catch (error) {
      } finally {
        loading.value = false;
      }
    },
  );
</script>

<style scoped lang="scss">
  :deep(
    .el-tabs.el-tabs--top
      > .el-tabs__header
      .el-tabs__nav-scroll
      .el-tabs__nav
      .el-tabs__active-bar
  ) {
    height: 3px;
  }
  :deep(.el-tabs__nav) {
    padding-right: 0px;
  }
  :deep(.el-tabs__nav-wrap:after) {
    height: 1px;
  }
  :deep(.el-tabs__header) {
    margin-bottom: 0px;
  }
  :deep(.el-tabs__item) {
    padding: 0px 24px 0px 0px;
  }
  :deep(.el-tabs) {
    --el-tabs-header-height: 30px;
  }

  .noData {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }
  .panel {
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    height: 100%;
    overflow: hidden;
    background: #ffffff;
    .left-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      position: relative;
      padding: 36px 0px 0px 24px;
      .left-arrow {
        position: absolute;
        top: 50%;
        right: -20px;
        cursor: pointer;
        z-index: 100;
      }
      .tab-title {
        flex: 1;
        font-size: 13px;
        color: #42464e;
        font-weight: 400;
        .tabs-detail {
          overflow: auto;
          height: calc(100vh - 150px);
        }
      }
    }

    .right-panel {
      box-sizing: border-box;
      width: 320px;
      max-height: 100%;
      overflow: auto;
      background: #f6f7fa;
      border: 1px solid #e6e6e6;
      padding: 24px;
      .right-header {
        box-sizing: border-box;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        width: 100%;
        margin-bottom: 5px;
      }
    }
  }

  .left-menu-container {
    box-sizing: border-box;
    position: absolute;
    right: 0px;
    width: 32px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: -10px 0px 16px rgba(0, 0, 0, 0.06);
    border-radius: 3px;
  }

  .left-menu {
    box-sizing: border-box;
    width: 32px;
    height: 116px;
    display: flex;
    flex-direction: column;
    align-items: center;
    top: 40%;
  }

  .menu-item {
    width: 24px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 2px 0;
    transition: all 0.3s ease;
    cursor: pointer;
    color: #626365;
    border: 1px solid transparent;
    border-radius: 3px;
    &:hover {
      background-color: #e8f1fb;
      color: #1aa1fb;
      border-color: #e8f1fb;
      img {
        filter: brightness(0) saturate(100%) invert(49%) sepia(92%)
          saturate(3618%) hue-rotate(190deg) brightness(104%) contrast(101%);
      }
    }
  }

  .menu-item.active {
    background-color: #e8f1fb;
    color: #1aa1fb;
    border-color: #e8f1fb;
  }

  .menu-item.active img {
    filter: brightness(0) saturate(100%) invert(49%) sepia(92%) saturate(3618%)
      hue-rotate(190deg) brightness(104%) contrast(101%);
  }

  .menu-icon {
    filter: invert(40%) sepia(0%) saturate(0%) hue-rotate(180deg)
      brightness(90%) contrast(90%);
  }

  .tab-content-scroll::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
  }
</style>

<style lang="scss">
  .is-drawer {
    margin-left: 24.9%;
  }
</style>
